<template>
  <view>
    <hx-navbar
      ref="hxnb"
      :config="config"
      @clickBtn="clickBtn"
      @onBack="onBack"
    ></hx-navbar>
    <view class="time-view">
      {{ time }}
    </view>
    <view class="form-view">
      <view
        class="form-item"
        @click="
          go('/pages/application/pages/personnel/custom/custom', {
            isJump: true,
          })
        "
      >
        <view class="label blue"> 客户 </view>
        <view
          class="value"
          :class="
            listData.billVo.auditState == true &&
            listData.billVo.isCancel == false
              ? 'c-99'
              : ''
          "
        >
          <text>{{ listData.billVo.comegoName }}</text>
        </view>
      </view>
      <view
        class="form-item"
        @click="
          go('/pages/application/pages/personnel/staff/staff', { isJump: true })
        "
      >
        <view class="label"> 业务员 </view>
        <view
          class="value"
          :class="
            listData.billVo.auditState == true &&
            listData.billVo.isCancel == false
              ? 'c-99'
              : ''
          "
        >
          <text>{{ listData.billVo.handUserName }}</text>
        </view>
      </view>
      <view
        class="form-item"
        @click="
          go(
            '/pages/application/pages/finance/accounts-receivable-payable/components/select-bank'
          )
        "
      >
        <view class="label"> 收款账户 </view>
        <view
          class="value"
          :class="
            listData.billVo.auditState == true &&
            listData.billVo.isCancel == false
              ? 'c-99'
              : ''
          "
        >
          <text
            v-for="(item, index) in listData.billVo.accountPaidList"
            :key="index"
          >
            {{ item.accountName }},
          </text>
        </view>
      </view>
      <view class="form-item">
        <view class="label"> 收款金额 </view>
        <view
          class="value"
          :class="
            listData.billVo.auditState == true &&
            listData.billVo.isCancel == false
              ? 'c-99'
              : ''
          "
        >
          <text>{{ totalAmountPaid }}</text>
        </view>
      </view>
      <view class="form-item">
        <view class="label"> 金额大写 </view>
        <view
          class="value"
          :class="
            listData.billVo.auditState == true &&
            listData.billVo.isCancel == false
              ? 'c-99'
              : ''
          "
        >
          <text>{{ convertToChinese }}</text>
        </view>
      </view>
      <view
        class="form-item"
        @click="
          getDocument(
            '/pages/application/pages/finance/accounts-receivable-payable/components/select-document'
          )
        "
      >
        <view class="label"> 选择单据 </view>
        <view
          class="value"
          :class="
            listData.billVo.auditState == true &&
            listData.billVo.isCancel == false
              ? 'c-99'
              : ''
          "
        >
          <text
            v-for="(item, index) in listData.passiveOffsetDetailList"
            :key="index"
          >
            {{ item.billTypeName }},
          </text>
        </view>
      </view>
      <!-- pages/application/pages/finance/components/other-expenses -->
      <view class="form-item" @click="onOther()">
        <view class="label blue"> 其他 </view>
        <view
          class="value"
          :class="
            listData.billVo.auditState == true &&
            listData.billVo.isCancel == false
              ? 'c-99'
              : ''
          "
        >
          <text
            v-for="(item, index) in listData.billVo.amountOtherList"
            :key="index"
          >
            {{ item.amountItemName }}-{{ item.amountPaid }},
          </text>
        </view>
      </view>
      <view class="form-item">
        <view class="flex col-item">
          <view class="label"> 前欠 </view>
          <view
            class="value"
            :class="
              listData.billVo.auditState == true &&
              listData.billVo.isCancel == false
                ? 'c-99'
                : ''
            "
          >
            {{ listData.billVo.comegoCurrentDebt || 0 }}
          </view>
        </view>
        <view class="flex col-item">
          <view class="label"> 累欠 </view>
          <view
            class="value"
            :class="
              listData.billVo.auditState == true &&
              listData.billVo.isCancel == false
                ? 'c-99'
                : ''
            "
          >
            {{ listData.billVo.comegoTotalDebt || 0 }}
          </view>
        </view>
      </view>
      <view class="form-item">
        <view class="label"> 对方账户 </view>
        <view
          class="value"
          :class="
            listData.billVo.auditState == true &&
            listData.billVo.isCancel == false
              ? 'c-99'
              : ''
          "
        >
          <u--input
            @focus="changInput"
            :color="
              listData.billVo.auditState == true &&
              listData.billVo.isCancel == false
                ? '#999'
                : ''
            "
            :disabled="
              listData.billVo.auditState == true &&
              listData.billVo.isCancel == false
            "
            v-model="listData.billVo.comegoAccountName"
            placeholder=""
            border="none"
          ></u--input>
        </view>
      </view>
      <view class="form-item">
        <view class="label"> 备注 </view>
        <view class="value">
          <u--input
            :color="
              listData.billVo.auditState == true &&
              listData.billVo.isCancel == false
                ? '#999'
                : ''
            "
            :disabled="
              listData.billVo.auditState == true &&
              listData.billVo.isCancel == false
            "
            @focus="changInput"
            v-model="listData.billVo.remarks"
            placeholder=""
            border="none"
          ></u--input>
        </view>
      </view>
    </view>
    <view class="fixed-btn flex">
      <!-- 详情、编辑 -->
      <u-button
        v-if="
          listData.billVo.auditState == false &&
          listData.billVo.isCancel == false &&
          id
        "
        text="审核"
        @click="audits()"
        type="primary"
        shape="circle"
        color="#ff9b00"
        border="none"
      ></u-button>

      <u-button
        v-if="
          listData.billVo.auditState == true &&
          listData.billVo.isCancel == false
        "
        text="作废"
        @click="
          () => {
            cancelShow = true;
          }
        "
        type="primary"
        shape="circle"
        color="#8d97a5"
      ></u-button>

      <u-button
        v-if="
          listData.billVo.auditState == false &&
          listData.billVo.isCancel == false &&
          !id
        "
        text="保存并审核1"
        class="card-btn"
        @click="updateItemData(0)"
        type="primary"
        shape="circle"
        color="#ddf0ff"
        border="none"
      ></u-button>
      <u-button
        v-if="
          listData.billVo.auditState == false &&
          listData.billVo.isCancel == false &&
          !id
        "
        text="保存"
        @click="updateItemData(1)"
        type="primary"
        shape="circle"
        class="save-btn"
        color="linear-gradient(to right, rgb(64, 158, 255), rgb(64, 158, 255), rgb(96, 180, 246), rgb(96, 180, 246))"
      ></u-button>

      <u-button
        v-if="
          listData.billVo.auditState == null &&
          listData.billVo.isCancel == null &&
          !id
        "
        text="保存并审核2"
        class="card-btn"
        @click="save(0)"
        type="primary"
        shape="circle"
        color="#ddf0ff"
        border="none"
      ></u-button>
      <u-button
        v-if="
          listData.billVo.auditState == null &&
          listData.billVo.isCancel == null &&
          !id
        "
        text="保存"
        @click="save(1)"
        type="primary"
        shape="circle"
        class="save-btn"
        color="linear-gradient(to right, rgb(64, 158, 255), rgb(64, 158, 255), rgb(96, 180, 246), rgb(96, 180, 246))"
      ></u-button>
    </view>
    <!-- 客户选择弹框 -->
    <u-popup
      :show="isLikeShow"
      mode="center"
      :round="5"
      @close="onLikeClose"
      :closeOnClickOverlay="true"
    >
      <view class="pop-ul">
        <view
          class="pop-li"
          :class="{ active: listData.billVo.comegoTypeId == item.value }"
          v-for="(item, index) in optList"
          :key="index"
          @click="onCheck(item)"
        >
          <u-icon
            name="checkbox-mark"
            color="#fff"
            class="m-r-20"
            size="24"
            v-if="listData.billVo.comegoTypeId == item.value"
          ></u-icon>
          {{ item.label }}
        </view>
      </view>
    </u-popup>
    <u-popup
      class="u-pop"
      :show="cancelShow"
      :round="10"
      mode="center"
      :closeOnClickOverlay="false"
    >
      <view class="popup-view">
        <view class="title" style="line-height: 282rpx">
          您确定要作废当前单据吗?
        </view>
        <view class="bot-view flex flex-sa">
          <view
            class="btn"
            @click="
              () => {
                cancelShow = false;
              }
            "
          >
            取消
          </view>
          <view class="btn" @click="cancels(false)"> 直接作废 </view>
          <view class="btn" @click="cancels(true)"> 重新做单 </view>
        </view>
      </view>
    </u-popup>
    <u-toast ref="uToast"></u-toast>
    <cx-delete-data
      @close="
        () => {
          deleteShow = false;
        }
      "
      :show="deleteShow"
      :id="listData.billVo.id"
      @delectDatalist="delectDatalist"
    ></cx-delete-data>
    <u-popup
      class="u-pop"
      :show="modalShow"
      :round="10"
      mode="center"
      :closeOnClickOverlay="false"
    >
      <view class="popup-view">
        <view class="title" style="line-height: 282rpx"> 您确定要保存吗? </view>
        <view class="bot-view flex flex-sa">
          <view
            class="btn"
            @click="
              () => {
                modalShow = false;
              }
            "
          >
            取消
          </view>
          <view class="btn" @click="toRoter()"> 不保存 </view>
          <view class="btn" @click="onSaveFun()"> 保存 </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import clIcon from "@/components/cl-icon/cl-icon.vue";
import cxDeleteData from "@/components/cx-delete-data/cx-delete-data.vue";
import { date, convertToChineseNumber } from "@/utils/util.js";
import {
  initAddBill,
  getLastRemainDebtTotal,
  addData,
  audit,
  getViewDataByBillId,
  cancel,
  updateData,
  deleteById,
} from "@/apis/bill/receipt";
import { comeGoType } from "@/apis/bill/payment-order";
export default {
  components: {
    clIcon,
    cxDeleteData,
  },
  data() {
    return {
      isLikeShow: false,
      optList: [],
      time: "",
      config: {
        title: "收款单",
        color: "#ffffff",
        // navigateBack: 1, // 返回的页面数  默认为1 返回上级  2返回上2级  3返回上3级
        navigateBack: null,
        // backTabPage:'', // 跳转到tab传这个参数
        // backPage:'', // 跳转到其他页面传这个参数
        //背景颜色;参数一：透明度（0-1）;参数二：背景颜色（array则为线性渐变，string为单色背景）
        backgroundColor: [1, ["#409EFF", "#409EFF", "#60b4f6", "#60b4f6"]],
        rightButton: [
          {
            key: "btn1",
            icon: "&#xe646;",
            position: "left",
          },
          {
            key: "btn2",
            txt: "",
            icon: "&#xed34;",
            // position: "left",
          },
        ],
      },
      listData: {
        billVo: {
          // "id": null,
          // "billNo": "SKD202307310002",
          // "shopId": "1666657492773502976",
          // "shopName": "总店",
          // "comegoTypeId": 0, // 左侧客户
          // "comegoTypeName": "客户", // 左侧客户
          // "comegoId": null,// 客户
          // "comegoName": "", // 客户
          // "comegoAccountName": "", //对方账户
          // "comegoCurrentDebt": 53700, //当前欠
          // "comegoTotalDebt": 63703, //累计欠
          // "amountPayable": null,
          // "amountPaid": 10000,
          // "amountTotal": "10000.00",
          // "remarks": "", // 备注
          // "isCancel": null,
          // "cancelTime": null,
          // "cancelUserId": null,
          // "cancelUserName": null,
          // "cancelCause": null,
          // "auditState": null,
          // "auditTime": null,
          // "auditUserId": null,
          // "auditUserName": null,
          // "handUserId": "", // 业务员
          // "handUserName": "", // 业务员
          // "businessTime": "2023-07-31 13:15:27",
          // "createUserId": null,
          // "createUserName": null,
          // "createTime": null,
          // "updateTime": null,
          // "updateUserId": null,
          // "updateUserName": null,
          // "accountPaidList": [
          //   {
          //     "accountName": "中行", // 账户
          //     "amountPaid": "10000", // 金额
          //     "accountId": "1666657493419425792" //账户id
          //   }
          // ],
          amountOtherList: [],
          // "accountNames": null,
          // "billId": null
        },
        passiveOffsetDetailList: [], //选择单据
      },
      id: null,
      // 作废按钮
      cancelShow: false,
      deleteShow: false,
      modalShow: false,
    };
  },
  computed: {
    totalAmountPaid() {
      if (!this.listData.billVo.accountPaidList) {
        return 0;
      }
      return this.listData.billVo.accountPaidList.reduce(
        (total, item) => Number(total) + Number(item.amountPaid),
        0
      );
    },
    convertToChinese() {
      if (!this.listData.billVo.accountPaidList) {
        return "";
      }
      return convertToChineseNumber(
        this.listData.billVo.accountPaidList.reduce(
          (total, item) => Number(total) + Number(item.amountPaid),
          0
        )
      );
    },
  },
  onLoad(opt) {
    this.getComeGoType();
    if (this.$Route.query.id) {
      this.id = this.$Route.query.id;
      this.currentIndex = 1;
      this.getViewDataByBillIds();
    } else {
      this.initAddBills();
    }
  },

  onShow() {},
  methods: {
    onSaveFun() {
      if (this.id) {
        this.save(1);
      } else {
        this.save(0);
      }
    },
    // 返回到主页面
    toRoter() {
      uni.switchTab({
        url: "/pages/application/index",
      });
    },
    // 左上角返回按钮
    onBack() {
      if (
        this.listData.billVo.auditState == null &&
        this.listData.billVo.isCancel == null
      ) {
        if (this.listData.length <= 0) {
          uni.switchTab({
            url: "/pages/application/index",
          });
          return;
        } else {
          this.modalShow = true;
        }
      } else {
        uni.switchTab({
          url: "/pages/application/index",
        });
      }
    },
    // 删除收款单
    delectDatalist() {
      let _this = this;
      _this.deleteShow = false;
      uni.showModal({
        content: "您确认删除当前单据吗?",
        success: function (res) {
          if (res.confirm) {
            deleteById(_this.listData.billVo.id).then((res) => {
              if (!res.flag) return;
              _this.$refs.uToast.show({
                type: "success",
                title: "",
                message: "删除成功",
                complete() {
                  uni.switchTab({
                    url: "/pages/application/index",
                  });
                },
              });
            });
          } else if (res.cancel) {
          }
        },
      });
    },
    clickBtn(item) {
      if (item.key === "btn1") {
        // this.printShow = true;
      } else if (item.key === "btn2") {
        this.deleteShow = !this.deleteShow;
      }
    },
    // 跳转到单据
    onOther() {
      if (this.listData.billVo.auditState && !this.listData.billVo.isCancel) {
        return;
      }
      uni.navigateTo({
        url:
          "/pages/application/pages/finance/accounts-receivable-payable/components/select-other-expenses?data=" +
          encodeURIComponent(
            JSON.stringify(this.listData.billVo.amountOtherList || [])
          ),
      });
    },
    // 获取供应商opts
    getComeGoType() {
      comeGoType().then((res) => {
        if (!res.flag) return;
        this.optList = res.data;
      });
    },
    // 显示客户置
    onLikeSet() {
      this.isLikeShow = true;
    },
    // 设置客户设置
    onCheck(val) {
      this.listData.billVo.comegoTypeName = val.label;
      this.listData.billVo.comegoTypeId = val.value;
      this.listData.billVo.comegoName = "";
      this.onLikeClose();
    },
    onLikeClose() {
      this.isLikeShow = false;
    },
    changInput() {
      if (
        this.listData.billVo.auditState == false &&
        this.listData.billVo.isCancel == false &&
        this.id
      ) {
        this.id = null;
      }
    },
    // 获取当前订单和时间
    getViewDataByBillIds() {
      getViewDataByBillId(this.id).then((res) => {
        if (!res.flag) return;
        const data = res.data || {};
        this.listData.billVo = Object.assign(this.listData.billVo, data.billVo);
        this.listData.passiveOffsetDetailList = data.passiveOffsetDetailList;
      });
    },
    cancels(show) {
      this.cancelShow = false;
      cancel({
        billId: this.id,
        isGenerateSameBill: show,
      }).then((res) => {
        if (!res.flag) return;
        const data = res.data || {};
        if (show) {
          this.id = data.id;
          this.getViewDataByBillIds();
        } else {
          this.$refs.uToast.show({
            type: "success",
            title: "",
            message: "作废成功",
            complete() {
              uni.switchTab({
                url: "/pages/application/index",
              });
            },
          });
        }
      });
    },
    audits() {
      let _this = this;
      uni.showModal({
        content: "您确认审核当前单据吗?",
        success: function (res) {
          if (res.confirm) {
            audit(_this.id).then((res) => {
              if (!res.flag) return;
              const data = res.data || {};
              _this.id = data.id;
              _this.getViewDataByBillIds();
              _this.$refs.uToast.show({
                type: "success",
                title: "",
                message: "审核成功",
              });
            });
          } else if (res.cancel) {
            console.log("用户点击取消");
          }
        },
      });
    },
    // 修改
    updateItemData(i) {
      updateData(this.listData).then((res) => {
        if (!res.flag) return;
        const data = res.data || {};
        this.id = data.id;
        if (i == 0) {
          this.audits();
        } else {
          this.getViewDataByBillIds();
          this.$refs.uToast.show({
            type: "success",
            title: "",
            message: "保存成功",
          });
        }
      });
    },
    save(i) {
      addData(this.listData).then((res) => {
        if (!res.flag) return;
        const data = res.data || {};
        this.id = data.id;
        if (i == 0) {
          this.audits();
        } else {
          this.getViewDataByBillIds();
          this.$refs.uToast.show({
            type: "success",
            title: "",
            message: "保存成功",
          });
        }
      });
    },
    // 页面跳转
    go(item, query = {} || []) {
      if (
        this.listData.billVo.auditState == true &&
        this.listData.billVo.isCancel == false
      ) {
        return;
      }
      this.$Router.push({
        path: item,
        query: query,
      });
    },
    getDocument(item) {
      if (
        this.listData.billVo.auditState == true &&
        this.listData.billVo.isCancel == false
      ) {
        return;
      }
      if (!this.listData.billVo.comegoId) {
        uni.showToast({
          icon: "error",
          title: "请先选择客户",
        });
        return;
      }
      this.$Router.push({
        path: item,
        query: {
          id: this.listData.billVo.comegoId,
          type: 2,
        },
      });
    },
    // 获取当前订单和时间
    initAddBills() {
      initAddBill().then((res) => {
        if (!res.flag) return;
        const data = res.data || {};
        this.listData.billVo = data;
      });
    },
    // 查询当前欠款
    getLastRemainDebtTotals() {
      getLastRemainDebtTotal({
        customerId: this.listData.billVo.comegoId,
        businessTime: this.listData.billVo.businessTime,
      }).then((res) => {
        if (!res.flag) return;
        // debugger
        const data = res.data;
        // 累欠 = 收款金额 - 累欠 - 其他单据费用
        // 收款金额
        let collectionAmount = this.listData.billVo.accountPaidList.reduce(
          (total, item) => Number(total) + Number(item.amountPaid),
          0
        );
        // 其他单据费用
        let otherAmount = 0;
        if (this.listData.billVo.amountOtherList) {
          otherAmount = this.listData.billVo.amountOtherList.reduce((total, item) => Number(total) + Number(item.amountPaid),0);
        }
        if(collectionAmount == 0){
          this.listData.billVo.comegoTotalDebt = data;
        }else{
          this.listData.billVo.comegoTotalDebt =  (data + otherAmount) - collectionAmount
        }
        
        this.listData.billVo.comegoCurrentDebt = data;
      });
    },
  },
  mounted() {
    this.time = date("Y-m-d H:i:s", new Date());

    uni.$on("pushCustomDetails", (data) => {
      this.listData.billVo.comegoId = data.id;
      this.listData.billVo.comegoName = data.name;
      this.getLastRemainDebtTotals();
      this.changInput();
    });
    uni.$on("on-staff-custom-details", (data) => {
      this.listData.billVo.handUserId = data.id;
      this.listData.billVo.handUserName = data.realName;
      this.changInput();
    });
    uni.$on("receiptSelectBank", (data) => {
      this.listData.billVo.accountPaidList = data;
      console.log("receiptSelectBank",data);
      console.log("this.listData.billVo.comegoCurrentDebt",this.listData.billVo.comegoCurrentDebt);
      if(this.listData.billVo.comegoCurrentDebt){
      let otherAmount = 0;
      let collectionAmount = this.listData.billVo.accountPaidList.reduce((total, item) => Number(total) + Number(item.amountPaid),0);
      if (this.listData.billVo.amountOtherList) {
        otherAmount = this.listData.billVo.amountOtherList.reduce((total, item) => Number(total) + Number(item.amountPaid),0);
      }
      this.listData.billVo.comegoTotalDebt = (this.listData.billVo.comegoCurrentDebt + otherAmount) - collectionAmount
      }

      this.changInput();
    });
    // 其他单据
    uni.$on("on-receipt-other-expenses", (data) => {
      this.listData.billVo.amountOtherList = data;
      console.log("on-receipt-other-expenses", data);
      if(this.listData.billVo.comegoCurrentDebt){
      let otherAmount = 0;
      let collectionAmount = this.listData.billVo.accountPaidList.reduce((total, item) => Number(total) + Number(item.amountPaid),0);
      if (this.listData.billVo.amountOtherList) {
        otherAmount = this.listData.billVo.amountOtherList.reduce((total, item) => Number(total) + Number(item.amountPaid),0);
      }
      this.listData.billVo.comegoTotalDebt = (this.listData.billVo.comegoCurrentDebt + otherAmount) - collectionAmount
      }
      this.changInput();
    });
    uni.$on("selectDocument", (data) => {
      this.listData.passiveOffsetDetailList = data;
      this.changInput();
    });
  },

  beforeDestroy() {
    uni.$off("pushCustomDetails");
    uni.$off("on-staff-custom-details");
    uni.$off("receiptSelectBank");
    uni.$off("on-receipt-other-expenses");
    uni.$off("selectDocument");
  },
};
</script>


<style lang="scss" scoped>
.fixed-btn {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 30rpx 20rpx;
  background: #fafafa;

  .card-btn {
    color: #409eff !important;
    border-radius: 40rpx 0 0 40rpx;
  }

  .save-btn {
    border-radius: 0 40rpx 40rpx 0;
  }
}

.time-view {
  background: linear-gradient(
    to right,
    rgb(64, 158, 255),
    rgb(64, 158, 255),
    rgb(96, 180, 246),
    rgb(96, 180, 246)
  );
  text-align: center;
  padding: 20rpx 0 30rpx;
  color: rgba(255, 255, 255, 0.6);
}

.form-view {
  background: #fff;
  overflow: hidden;

  .form-item {
    display: flex;
    border-bottom: 1rpx solid #ddd;
    padding: 24rpx 40rpx;
    align-items: center;
    font-size: 30rpx;

    .label {
      color: #999;
      flex: 1.5;
      text-align: right;
      padding-right: 18rpx;
    }

    .value {
      flex: 6;
      display: flex;
      min-width: 100px;
      height: 20px;
    }

    .category {
      justify-content: space-between;
    }

    .col-item {
      flex: 1;

      .value {
        flex: 2.4;
        min-width: 100px;
        height: 20px;
      }
    }
  }
}
</style>